package cn.t.core.enums.base;

import cn.t.core.enums.EnumData;
import cn.t.core.enums.EnumStore;
import cn.t.core.enums.Enumer;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Slf4j
public class EnumScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {

    private ResourceLoader resourceLoader;
    private Environment environment;
    private BeanNameGenerator beanNameGenerator;
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        beanNameGenerator = AnnotationBeanNameGenerator.INSTANCE;
        AnnotationAttributes mapperScanAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnumScan.class.getName()));
        if (mapperScanAttrs != null) {
            String[] basePackages = mapperScanAttrs.getStringArray("basePackages");

            EnumScanner enumScanner = new EnumScanner(false, environment);
            enumScanner.setResourceLoader(resourceLoader);
            enumScanner.addIncludeFilter(new AnnotationTypeFilter(Enumer.class));
            for (String basePackage : basePackages) {
                Set<BeanDefinition> definitions = enumScanner.findCandidateComponents(basePackage);
                for (BeanDefinition definition : definitions) {
                    try {
                        String className = definition.getBeanClassName();
                        String beanName = this.beanNameGenerator.generateBeanName(definition, registry);
                        Class clazz = Class.forName(className);
                        Class[] interfaces = clazz.getInterfaces();
                        if (interfaces == null || interfaces.length == 0) {
                            log.error("{}未实现CommonEnum接口", className);
                            continue;
                        }
                        List<Class> classes = Arrays.asList(interfaces);
                        if (!classes.contains(CommonEnum.class)) {
                            log.error("{}未实现CommonEnum接口", className);
                            continue;
                        }

                        Object[] enumConstants = clazz.getEnumConstants();
                        Method getCode = clazz.getMethod("getCode");
                        Method getName = clazz.getMethod("getName");

                        List<EnumData> datas = Lists.newArrayList();
                        for (Object enumConstant : enumConstants) {
                            datas.add(EnumData.getInstance(String.valueOf(getCode.invoke(enumConstant)), String.valueOf(getName.invoke(enumConstant))));
                        }

                        EnumStore.addEnum(beanName, datas);
                    } catch (Exception e) {
                        log.error("{}读取异常", definition.getBeanClassName());
                    }
                }
            }
        }
    }
}
